package mcjunkin.gui;
import mcjunkin.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

/**
	This is a JPanel that shows the current status of the application.
*/

public class StatusWidget extends JPanel implements StatusListener {

	//swing elements
	private JLabel message1, message2;
	private JProgressBar memory;
	
	/** Constructor builds the panel. */
	public StatusWidget(){
		
		setLayout(new GridLayout(1,3));

		//create a message1 label
		message1 = new JLabel("message");
		message1.setBorder(BorderFactory.createEmptyBorder(4,4,4,4)); //TLBR	
		this.add(message1);

		//create a message2 label
		message2 = new JLabel("matches");
		message2.setBorder(BorderFactory.createEmptyBorder(4,4,4,4)); //TLBR	
		this.add(message2);
	
		//make a progress bar
		memory = new JProgressBar(0,100);
		memory.setValue(0);
		memory.setStringPainted(true);
		memory.setBorder(BorderFactory.createEmptyBorder(4,4,4,4)); //TLBR
		this.add(memory);	
		
		//constrain the size of this panel
		this.setMaximumSize(new Dimension(Integer.MAX_VALUE,80));
	}
	
	/** Set message 1 */
	public void setMessage1(String s){
		message1.setText(s);
	}
		
	/** Set message 2 */
	public void setMessage2(String s){
		message2.setText(s);
	}
	
	/** Incoming notification */
	public void message(String s){
		setMessage1(s);
	}
		
	/** Incoming notification */
	public void tableSizes(long dirs, long files){
		setMessage2("Holding "+dirs+"dirs /"+files+" files");
	}

	/** Update memory usage */
	public void updateMemory(){
		long total = Runtime.getRuntime().totalMemory();
		long used = total - Runtime.getRuntime().freeMemory();
		double value = ((double)used)/((double)total)*100.0;
		memory.setValue((int)value);
		memory.setStringPainted(true);
		memory.setString(readableFileSize(used)+"/"+
			readableFileSize(total));		
	}

	//helper to format file size into KB/MB/TB
	// http://stackoverflow.com/questions/3263892/format-file-size-as-mb-gb-etc
	private static String readableFileSize(long size) {
		if(size <= 0) return "0";
		final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
		int digitGroups = (int) (Math.log10(size)/Math.log10(1024));
		return new java.text.DecimalFormat("#,##0.#").format(size/
			Math.pow(1024, digitGroups)) + " " + units[digitGroups];
	}
	
}
